<?php
class Current_User {

	private static $user;
	public static $administrtor = 1;

	public function __construct() {}

	public static function user() {

		if(!isset(self::$user)) {

			$CI =& get_instance();
			//$CI->load->library('session');

			if (!$user_id = $CI->session->userdata('user_id')) {
				return FALSE;
			}
			
			if (!$u = $CI->db->select()->from('user')->where('user_id', $user_id)->get()->row_object()) {
			//if( !$u = $CI->doctrine->em->find('Entities\User', $user_id)) {
				return FALSE;
			}

			self::$user = $u;
		}
		
		return self::$user;
	}

	public static function login($username, $password) {

		$CI =& get_instance();
		
		if ($u = $CI->db->select()->from('user')->where('account', $username)->get()->row_object()) {
		//if ($u = $CI->doctrine->em->getRepository('Entities\User')->findOneBy(array('account' => $username))) {
			if ($u->password == md5($password)) {
				
				$CI->load->library('session');
				$CI->session->set_userdata('user_id',$u->user_id);
				self::$user = $u;

				return TRUE;
			}

			//unset($u_input);
		}

		// login failed
		return FALSE;

	}
	
	public static function my_role() {
		$CI =& get_instance();
		
		$u = Current_User::user();
		$CI->load->model('user');
		$role = $CI->user->get_role($u->role_id);
		return ($role ? $role->id : '');
	}

	public function __clone() {
		trigger_error('Clone is not allowed.', E_USER_ERROR);
	}

}
